package sjd.ahsj.springbootmybatisplusoracle.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sjd.ahsj.springbootmybatisplusoracle.entity.IUser;
import sjd.ahsj.springbootmybatisplusoracle.interceptor.BaseContextHandler;
import sjd.ahsj.springbootmybatisplusoracle.interceptor.IgnoreAuth;
import sjd.ahsj.springbootmybatisplusoracle.model.ReturnObject;
import sjd.ahsj.springbootmybatisplusoracle.service.IIUserService;
import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zhanghaogao
 * @since 2018-11-12
 */
@Api(description = "用户")
@RestController
@RequestMapping("/iUser")
public class IUserController {

    @Autowired
    private IIUserService iiUserService;


    @IgnoreAuth
    @ApiOperation("登陆")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ReturnObject login(@ApiParam("密码") @RequestParam String password,
                              @ApiParam("用户名") @RequestParam String username) throws
            UnsupportedEncodingException, NoSuchAlgorithmException {
        IUser baseUsers = iiUserService.selectOne(new EntityWrapper<IUser>().eq("name", username).eq
                ("password", EncoderByMd5(password)));
        if (baseUsers == null) {
            return new ReturnObject(1, "用户名、密码错误");
        }
        return new ReturnObject(0, "登陆成功", baseUsers.getId());
    }


    @ApiOperation("重置密码")
    @RequestMapping(value = "/resetPassword", method = RequestMethod.POST)
    public ReturnObject resetPassword(@ApiParam("用户id") @RequestParam Integer id,
                                      @ApiParam("新密码") @RequestParam String password) throws
            UnsupportedEncodingException, NoSuchAlgorithmException {

        IUser baseUsers = iiUserService.selectById(id);
        if (baseUsers == null) {
            return new ReturnObject(1, "用户不存在");
        }
        baseUsers.setPassword(EncoderByMd5(password));
        iiUserService.updateById(baseUsers);
        return new ReturnObject(0, "密码修改成功", baseUsers.getId());
    }

    @ApiOperation("修改密码")
    @RequestMapping(value = "/changePassword", method = RequestMethod.POST)
    public ReturnObject changePassword(@ApiParam("原密码") @RequestParam String oldPassword,
                                       @ApiParam("新密码") @RequestParam String password) throws
            UnsupportedEncodingException, NoSuchAlgorithmException {

        IUser baseUsers = iiUserService.selectById(BaseContextHandler.getUserID());
        if (baseUsers == null) {
            return new ReturnObject(1, "用户不存在");
        }
        if (!baseUsers.getPassword().equals(EncoderByMd5(oldPassword))) {
            return new ReturnObject(1, "原密码错误");
        }
        baseUsers.setPassword(EncoderByMd5(password));
        iiUserService.updateById(baseUsers);
        return new ReturnObject(0, "密码修改成功", baseUsers.getId());
    }


    @ApiOperation("获取用户信息")
    @RequestMapping(value = "/getInfo", method = RequestMethod.POST)
    public ReturnObject getInfo() {
        IUser baseUsers = iiUserService.selectById(BaseContextHandler.getUserID());
        return new ReturnObject(0, "", baseUsers);
    }


    @ApiOperation("设置用户查看电站")
    @RequestMapping(value = "/getUserFactory", method = RequestMethod.POST)
    public ReturnObject getUserFactory(@ApiParam("电站id多个逗号隔开") @RequestParam String factoryId,
                                       @ApiParam("用户id") @RequestParam Integer userId) {
        IUser baseUsers = iiUserService.selectById(userId);
        baseUsers.setFactoryId(factoryId);
        iiUserService.updateById(baseUsers);
        return new ReturnObject(0, "", baseUsers);
    }


    @IgnoreAuth
    @ApiOperation("新增用户")
    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
    public ReturnObject addUser(@ApiParam("电站id多个逗号隔开") @RequestParam String factoryId,
                                @ApiParam("账号") @RequestParam String userName,
                                @ApiParam("密码") @RequestParam String password,
                                @ApiParam("权限（0：普通用户，1：管理员）") @RequestParam String code) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        if (iiUserService.selectCount(new EntityWrapper<IUser>().eq("name", userName)) > 0) {
            return new ReturnObject(1, "用户名重复，无法新增");
        }
        IUser baseUsers = new IUser();
        baseUsers.setName(userName);
        baseUsers.setCode(code);
        baseUsers.setPassword(EncoderByMd5(password));
        baseUsers.setFactoryId(factoryId);
        iiUserService.insert(baseUsers);
        return new ReturnObject(0, "用户增加成功", baseUsers);
    }


    @ApiOperation("获取用户")
    @RequestMapping(value = "/getUserPage", method = RequestMethod.POST)
    public ReturnObject<List<IUser>> getUserPage(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                                 @ApiParam("页数") @RequestParam(defaultValue = "1") int offset) {
        EntityWrapper<IUser> ew = new EntityWrapper<>();
        Page<IUser> obj = iiUserService.selectPage(new Page<>(offset, limit), ew);
        return new ReturnObject<>(0, "获取成功", obj.getTotal(), obj.getPages(), obj.getRecords());
    }

    public String EncoderByMd5(String str) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        //确定计算方法
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        BASE64Encoder base64en = new BASE64Encoder();
        //加密后的字符串
        String newstr = base64en.encode(md5.digest(str.getBytes("utf-8")));
        return newstr;
    }
}

